package com.fingard.dsp.bank.directbank.hzcb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IElecBillQuery;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.*;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB001OperBillQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB005BillBackQryDetail;
import com.fingard.dsp.bank.reqrespobj.elecbillquery.detail.RetAtsB006BillStateQryDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import com.spire.ms.System.Collections.ArrayList;

import java.sql.Connection;
import java.util.*;

/**
 * @author Parker on 2020-04-03.
 * @version 1.0
 */
public class HZCB01ElecBill extends HZCB01Base implements IElecBillQuery {

    /**
     * 可操作票据查询
     * 业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
     * 查询类型 1-申请 2-应答 3-撤回
     */
    @Override
    public RetAtsB001OperBillQry D_OperBill_Query_Req(ReqB001OperBillQry query) throws Exception {
        RetAtsB001OperBillQry retAts = new RetAtsB001OperBillQry(query.reqHeader);
        String respCode = "";
        String respInfo = "";
        retAts.respCode = "0";
        retAts.writeBefore();
        Connection conn = FGBiz.getLocalDbConn();
        List<String> billNos = new ArrayList();//记录票号，去重
        while (query.readRecord()) {
            try {
                List<String> transTypes = getTransType(query);
                for (String transType : transTypes) {
                    int totalPages = 0;
                    int currentPage = 0;
                    do {
                        currentPage++;
                        XmlTextWriter xmlWriter = null;
                        if ("2".equals(query.detail.queryType)) {
                            xmlWriter = qryByPY4027(query, currentPage, transType);//发银行报文的XML对象
                        } else {
                            xmlWriter = qryByPY4031(query, currentPage, transType);//发银行报文的XML对象
                        }

                        String signXml = getDataSignData(xmlWriter);
                        if (signnatrue(signXml) == true) {
                            xmlWriter.writeElementString("signData", signature);
                            xmlWriter.writeEndDocument();//写入数据完成
                            String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                            if (tmpStrRet[0].length() == 0) {
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                                if (tmpBkReader != null) {
                                    String tmprspcod = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                                    String tmprspmsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                                    if (tmprspcod != null && isActiveRetCode(tmprspcod)) {
                                        totalPages = Integer.parseInt(tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/totalPages"));
                                        while (tmpBkReader.read("/HZBANKB2C/ebank/output/result/row")) {
                                            String billType = tmpBkReader.readedXElement.getSingleTextNotNull("billType");
                                            if (query.detail.billType.equals(billType)) {
                                                String billId = tmpBkReader.readedXElement.getSingleTextNotNull("billId");
                                                if (!billNos.contains(billId)) {//去重
                                                    billNos.add(billId);
                                                    RetAtsB001OperBillQryDetail detail = new RetAtsB001OperBillQryDetail();
                                                    detail.billNo = tmpBkReader.readedXElement.getSingleTextNotNull("billNo");//电子票据号码
                                                    boolean isSendToBank = true;
                                                    try {
                                                        Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{detail.billNo, query.reqHeader.bankCode});
                                                        if (selMap.size() == 0) {
                                                            //记录ats支付流水号对应的银行指令流水号，供查询状态接口使用
                                                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                                            int count = JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, query.reqHeader.bankCode, Format.Date8Format.format(new Date()), detail.billNo, billId});
                                                            if (count < 1) {
                                                                isSendToBank = false;
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        isSendToBank = false;
                                                    }
                                                    if (!isSendToBank) {
                                                        WriteBankLogLn("票据ID" + billId + "与票据号" + detail.billNo + "映射失败");
                                                    }
                                                    detail.billType = tmpBkReader.readedXElement.getSingleTextNotNull("billType");//票据类型 1-银承 2-商承
                                                    detail.issDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("acptDt"));//出票日(yyyy-MM-dd)
                                                    detail.dueDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("dueDt"));//到期日(yyyy-MM-dd)
                                                    detail.billAmt = tmpBkReader.readedXElement.getSingleTextNotNull("billMoney");//电子票据金额
                                                    detail.transFlag = "0".equals(tmpBkReader.readedXElement.getSingleTextNotNull("forbidFlag")) ? "1" : "0";//背书转让标识 1-可再转让 0-不得转让
                                                    if ("2".equals(query.detail.busiType)) {
                                                        detail.mustPay = "1";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                                    }
                                                    detail.drawName = tmpBkReader.readedXElement.getSingleTextNotNull("remitter");//出票人
//                                                detail.drawCode = tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                                    detail.drawAct = tmpBkReader.readedXElement.getSingleTextNotNull("remitterAcctNo");//出票人账号
                                                    detail.drawBnkName = tmpBkReader.readedXElement.getSingleTextNotNull("remitterBankName");//出票人开户行行名
                                                    detail.drawBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("remitterBankNo");//出票人开户行行号
                                                    detail.accpName = tmpBkReader.readedXElement.getSingleTextNotNull("acceptor");//承兑人名称
//                                                detail.accpCode = tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpcod");//承兑人组织代码
                                                    detail.accpAct = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorAcctNo");//承兑人账号
                                                    detail.accpBnkName = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorBankName");//承兑人开户行行名
                                                    detail.accpBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorBankNo");//承兑人开户行行号
                                                    detail.payeeName = tmpBkReader.readedXElement.getSingleTextNotNull("payee");//收款人
//                                                detail.payeeCode = tmpBkReader.readedXElement.getSingleTextNotNull("Stdpyeecod");//
                                                    detail.payeeAct = tmpBkReader.readedXElement.getSingleTextNotNull("payeeAcctNo");//收款人账号
                                                    detail.payeeBnkName = tmpBkReader.readedXElement.getSingleTextNotNull("payeeBankName");//收款人开户行行名
                                                    detail.payeeBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("payeeBankNo");//收款人开户行行号
                                                    detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                                    detail.applyName = tmpBkReader.readedXElement.getSingleTextNotNull("fromName");//申请人
//                                                detail.applyCode = tmpBkReader.readedXElement.getSingleTextNotNull("Stdappcode");//申请人组织机构代码
                                                    detail.applyAct = tmpBkReader.readedXElement.getSingleTextNotNull("fromAcctNo");//申请人账号
                                                    detail.applyBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("fromBankNo");//申请人开户行行号
//                                                detail.busiNo = tmpBkReader.readedXElement.getSingleTextNotNull("");//交易明细流水
                                                    detail.busiType = query.detail.busiType;//操作标志
                                                    detail.queryType = query.detail.queryType;//查询类型
//                                                detail.memo = tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrmem");//备注
                                                    detail.billStatus = getBillStatus(query.detail.actNum, tmpBkReader.readedXElement.getSingleTextNotNull("billId"), query.reqHeader);//票据状态
                                                    retAts.writeDetail(detail);
                                                }
                                            }
                                        }
                                    } else {
                                        respCode = "-1";
                                        respInfo = tmprspmsg;
                                    }
                                } else {
                                    respCode = "-1";
                                    respInfo = tmpSbMsg.toString();
                                }
                            } else {
                                respCode = "-1";
                                respInfo = tmpStrRet[1];
                            }
                        } else {
                            respCode = "-1";
                            respInfo = tmpSign[1];
                        }
                    } while (currentPage < totalPages);
                }
            } catch (Exception e) {
                respCode = "-1";
                respInfo = e.getMessage();
            } finally {
                if (conn != null) {
                    conn.close();
                }

            }
            if ("-1".equals(respCode)) {
                retAts = new RetAtsB001OperBillQry(query.reqHeader);
                retAts.respCode = "-1";
                retAts.respInfo = respInfo;
                retAts.writeBefore();
                retAts.writeEnd();
                return retAts;
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    private XmlTextWriter qryByPY4027(ReqB001OperBillQry query, int currentPage, String transType) throws Exception {
        txCode = "PY4027";
        XmlTextWriter xmlWriter = new XmlTextWriter();
        //写入通用的头部节点
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("input");
        xmlWriter.writeElementString("compFlowNo", query.reqHeader.transSeqID);//企业流水号
        xmlWriter.writeElementString("applicantAcctNo", query.detail.actNum);//客户账号
        xmlWriter.writeElementString("billNo", "");//票号
        xmlWriter.writeElementString("transNo", transType);//交易类型
        int monthLength = getBankConfig().getValueAsInt("DateBeforeNow", 3);
        Date date = new Date();//获取当前时间    
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -monthLength);//当前时间前去一个月，即一个月前的时间
        xmlWriter.writeElementString("maxAcptDt", Format.Date8Format.format(date));//出票日期上限
        xmlWriter.writeElementString("minAcptDt", Format.Date8Format.format(calendar.getTime()));//出票日期下限
        xmlWriter.writeElementString("maxDueDt", "");//汇票到期日上限
        xmlWriter.writeElementString("minDueDt", "");//汇票到期日下限
        xmlWriter.writeElementString("maxBillMoney", "");//票据金额上限
        xmlWriter.writeElementString("minBillMoney", "");//票据金额下限
        xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
        xmlWriter.writeElementString("currentPage", String.valueOf(currentPage));
        xmlWriter.writeElementString("reserve1", "");
        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();
        return xmlWriter;
    }

    private XmlTextWriter qryByPY4031(ReqB001OperBillQry query, int currentPage, String transType) throws Exception {
        txCode = "PY4031";
        XmlTextWriter xmlWriter = new XmlTextWriter();
        //写入通用的头部节点
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("input");
        xmlWriter.writeElementString("compFlowNo", query.reqHeader.transSeqID);//企业流水号
        xmlWriter.writeElementString("applicantAcctNo", query.detail.actNum);//客户账号
        xmlWriter.writeElementString("transNo", transType);//交易类型
        xmlWriter.writeElementString("remitter", "");//出票人全称
        xmlWriter.writeElementString("payee", "");//收款人全称
        xmlWriter.writeElementString("draweeBankName", "");//付款行行名
        xmlWriter.writeElementString("billNo", "");//票号
        int monthLength = getBankConfig().getValueAsInt("DateBeforeNow", 3);
        Date date = new Date();//获取当前时间    
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -monthLength);//当前时间前去一个月，即一个月前的时间
        xmlWriter.writeElementString("maxAcptDt", Format.Date8Format.format(date));//出票日期上限
        xmlWriter.writeElementString("minAcptDt", Format.Date8Format.format(calendar.getTime()));//出票日期下限
        xmlWriter.writeElementString("maxDueDt", "");//汇票到期日上限
        xmlWriter.writeElementString("minDueDt", "");//汇票到期日下限
        xmlWriter.writeElementString("maxBillMoney", "");//票据金额上限
        xmlWriter.writeElementString("minBillMoney", "");//票据金额下限
        xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
        xmlWriter.writeElementString("currentPage", String.valueOf(currentPage));

        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();
        return xmlWriter;
    }

    //票据操作明细查询
    @Override
    public RetAtsB002BillTransQry D_B002_BillTrans_Query(ReqB002BillTransQry query) throws Exception {
        RetAtsB002BillTransQry retAts = new RetAtsB002BillTransQry(query.reqHeader);
        retAts.respCode = "-1";
        retAts.respInfo = "暂不支持";
        retAts.writeStart();
        retAts.writeAfter();
        return retAts;
    }

    //正面信息查询
    @Override
    public RetAtsB004BillFrontQry D_B004_BillFront_Query(ReqB004BillFrontQry query) throws Exception {
        RetAtsB004BillFrontQry retAts = new RetAtsB004BillFrontQry(query.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            while (query.readRecord()) {
                txCode = "PY4023";
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("input");
                xmlWriter.writeElementString("compFlowNo", query.reqHeader.transSeqID);//企业流水号
                Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{query.detail.billNo, query.reqHeader.bankCode});
                if (map.size() == 0) {
                    retAts.respCode = "0";
                    retAts.respInfo = "没有找到票据号对应的票据ID号！";
                    retAts.writeEnd();
                    return retAts;
                }
                xmlWriter.writeElementString("billId", map.get("BANKREQSEQID").toString());//票据ID
                xmlWriter.writeElementString("applicantAcctNo", query.detail.actNum);//客户账号
                xmlWriter.writeEndElement();
                xmlWriter.writeEndElement();
                String signXml = getDataSignData(xmlWriter);
                if (signnatrue(signXml) == true) {
                    xmlWriter.writeElementString("signData", signature);
                    xmlWriter.writeEndDocument();//写入数据完成
                    String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmprspcod = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                            String tmprspmsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                            if (tmprspcod != null && isActiveRetCode(tmprspcod)) {
                                retAts.respCode = "0";
                                while (tmpBkReader.read("/HZBANKB2C/ebank/output")) {
                                    retAts.billNo = tmpBkReader.readedXElement.getSingleTextNotNull("billNo");//电子票据
                                    retAts.billType = tmpBkReader.readedXElement.getSingleTextNotNull("billType");//票据类型 1-银承 2-商承
                                    retAts.issDate = tmpBkReader.readedXElement.getSingleTextNotNull("acptDt");//出票日
                                    retAts.dueDate = tmpBkReader.readedXElement.getSingleTextNotNull("dueDt");//到期日
                                    retAts.billAmt = tmpBkReader.readedXElement.getSingleTextNotNull("billMoney");//电子票据金额
                                    retAts.transFlag = "0".equals(tmpBkReader.readedXElement.getSingleTextNotNull("forbidFlag")) ? "1" : "2";//背书转让标识 1-可再转让 0-不得转让
                                    retAts.mustPay = "1";//承兑无条件支付委托 1-无条件支付 0-非条件支付
                                    retAts.drawName = tmpBkReader.readedXElement.getSingleTextNotNull("remitter");//出票人
                                    //retAts.drawCode = tmpBkReader.readedXElement.getSingleTextNotNull("Stddrwrcod");//出票人组织代码
                                    retAts.drawAct = tmpBkReader.readedXElement.getSingleTextNotNull("remitterAcctNo");//出票人账号
                                    retAts.drawBnkName = tmpBkReader.readedXElement.getSingleTextNotNull("remitterBankName");//出票人开户行行名
                                    retAts.drawBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("remitterBankNo");//出票人开户行行号
                                    retAts.creditLv = tmpBkReader.readedXElement.getSingleTextNotNull("remitterCreditRatgs");//出票人信用等级
//                                    retAts.gradeAgent = tmpBkReader.readedXElement.getSingleTextNotNull("Stddrragcy");//出票人信用评级机构
                                    retAts.gradeDueDate = tmpBkReader.readedXElement.getSingleTextNotNull("remitterRatgDuedt");//出票人评级到期日
                                    retAts.drGuarName = tmpBkReader.readedXElement.getSingleTextNotNull("remitterAssuName");//出票保证人名称
                                    retAts.drGuarAddr = tmpBkReader.readedXElement.getSingleTextNotNull("remitterAssuAddr");//出票保证人地址
                                    retAts.drGuarDate = tmpBkReader.readedXElement.getSingleTextNotNull("remitterAssuDt");//出票保证日期
                                    retAts.accpName = tmpBkReader.readedXElement.getSingleTextNotNull("acceptor");//承兑人名称
                                    retAts.accpAct = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorAcctNo");//承兑人账号
                                    retAts.accpBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorBankNo");//承兑人开户行行号
//                                    retAts.accpCredit = tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccprat");//承兑人信用等级
//                                    retAts.accpGradeDue = tmpBkReader.readedXElement.getSingleTextNotNull("Stdaccpdue");//承兑人评级到期日
                                    retAts.apGuarName = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorAssuName");//承兑保证人名称
                                    retAts.apGuarAddr = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorAssuAddr");//承兑保证人地址
                                    retAts.apGuarDate = tmpBkReader.readedXElement.getSingleTextNotNull("acceptorAssuDt");//承兑保证日期
                                    retAts.payeeName = tmpBkReader.readedXElement.getSingleTextNotNull("payee");//收款人名称
                                    retAts.payeeAct = tmpBkReader.readedXElement.getSingleTextNotNull("payeeAcctNo");//收款人账号
                                    retAts.payeeBnkName = tmpBkReader.readedXElement.getSingleTextNotNull("payeeBankName");//收款人开户行行名
                                    retAts.payeeBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("payeeBankNo");//收款人开户行行号
                                    retAts.billState = tmpBkReader.readedXElement.getSingleTextNotNull("status");//票据状态
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmprspmsg;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStrRet[1];
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSign[1];
                }
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeRetDetail();
        retAts.writeEnd();
        return retAts;
    }

    //票据背面信息查询
    @Override
    public RetAtsB005BillBackQry D_B005_BillBack_Query(ReqB005BillBackQry query) throws Exception {
        RetAtsB005BillBackQry retAts = new RetAtsB005BillBackQry(query.reqHeader);
        retAts.writeBeforeDetail();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            while (query.readRecord()) {
                int totalPages = 0;
                int currentPage = 0;
                do {
                    currentPage++;
                    txCode = "PY4024";
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeStartElement("input");
                    xmlWriter.writeElementString("compFlowNo", query.reqHeader.transSeqID);
                    xmlWriter.writeElementString("applicantAcctNo", query.detail.actNum);
                    Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{query.detail.billNo, query.reqHeader.bankCode});
                    RetAtsB005BillBackQryDetail detail = null;
                    if (map.size() == 0) {
                        detail = new RetAtsB005BillBackQryDetail();
                        detail.respCode = "0";
                        detail.respInfo = "没有找到票据号对应的票据ID号！";
                        retAts.writeDetail(detail);
                        retAts.writeEnd();
                        return retAts;
                    }
                    xmlWriter.writeElementString("billId", map.get("BANKREQSEQID").toString());//票据ID
                    xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
                    xmlWriter.writeElementString("currentPage", String.valueOf(currentPage));
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();
                    String signXml = getDataSignData(xmlWriter);
                    if (signnatrue(signXml) == true) {
                        xmlWriter.writeElementString("signData", signature);
                        xmlWriter.writeEndDocument();//写入数据完成
                        String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                        if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmprspcod = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                                String tmprspmsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                                if (tmprspcod != null && isActiveRetCode(tmprspcod)) {
                                    totalPages = Integer.parseInt(tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/totalPages"));
                                    retAts.writeRespCode("0");
                                    while (tmpBkReader.read("/HZBANKB2C/ebank/output/result/row")) {
                                        detail = new RetAtsB005BillBackQryDetail();
                                        detail.respCode = "0";
                                        detail.respInfo = "";
                                        detail.billNo = query.detail.billNo;//电子票据号码
                                        detail.transCode = getTransCode(tmpBkReader.readedXElement.getSingleTextNotNull("transNo"));
                                        detail.applyName = tmpBkReader.readedXElement.getSingleTextNotNull("name");//申请人

                                        if ("17".equals(detail.transCode)) {//保证
                                            detail.receName = tmpBkReader.readedXElement.getSingleTextNotNull("toName");//接收人
                                            detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                            detail.guarAddr = tmpBkReader.readedXElement.getSingleTextNotNull("assuSignerAddr");//地址
                                        } else if ("18".equals(detail.transCode)) {//质押
                                            detail.receName = tmpBkReader.readedXElement.getSingleTextNotNull("toName");//接收人
                                            detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                        } else if ("20".equals(detail.transCode)) {//提示付款
                                            detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                            detail.respFlag = "0".equals(tmpBkReader.readedXElement.getSingleTextNotNull("presentationFlag")) ? "1" : "2";//应答标记 1--签收 2--驳回
                                            detail.respDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("finishDt"));//操作日期
                                        } else if ("22".equals(detail.transCode)) {//追索
                                            detail.receName = tmpBkReader.readedXElement.getSingleTextNotNull("toName");//接收人
                                            detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                            detail.respDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("finishDt"));
                                            detail.recourseType = "0".equals(tmpBkReader.readedXElement.getSingleTextNotNull("recourseType")) ? "2" : "1";
                                        } else {//背书
                                            detail.receName = tmpBkReader.readedXElement.getSingleTextNotNull("toName");//接收人
                                            detail.applyDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("applyDt"));//申请日期
                                            detail.transFlag = "0".equals(tmpBkReader.readedXElement.getSingleTextNotNull("forbidFlag")) ? "1" : "0";
                                        }
                                        retAts.writeDetail(detail);
                                    }
                                } else {
                                    detail.respCode = "-1";
                                    detail.respInfo = tmprspmsg;
                                    retAts.writeDetail(detail);
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = tmpSbMsg.toString();
                                retAts.writeDetail(detail);
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = tmpStrRet[1];
                            retAts.writeDetail(detail);
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSign[1];
                        retAts.writeDetail(detail);
                    }
                } while (currentPage < totalPages);
            }
        } catch (Exception e) {
            RetAtsB005BillBackQryDetail detail = new RetAtsB005BillBackQryDetail();
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            retAts.writeDetail(detail);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    //票据交易状态查询
    @Override
    public RetAtsB006BillStateQry D_B006_BillState_Qeury(ReqB006BillStateQry query) throws Exception {
        RetAtsB006BillStateQry retAts = new RetAtsB006BillStateQry(query.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            while (query.readRecord()) {
                int totalPages = 0;
                int currentPage = 0;
                do {
                    currentPage++;
                    RetAtsB006BillStateQryDetail detail = new RetAtsB006BillStateQryDetail();
                    txCode = "PY4025";
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter);
                    xmlWriter.writeStartElement("input");
                    xmlWriter.writeElementString("compFlowNo", query.detail.reqSeqID);
                    Map<String, Object> map = null;
                    if ("1".equals(query.detail.busiType)) {
                        map = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{query.detail.reqSeqID, query.reqHeader.bankCode});
                        if (map.size() == 0) {
                            detail.respCode = "0";
                            detail.respInfo = "没有找到流水号对应的票据ID号！";
                            retAts.writeDetail(detail);
                            retAts.writeEnd();
                            return retAts;
                        }
                        xmlWriter.writeElementString("billId", map.get("BANKREQSEQID").toString());//票据ID
                        xmlWriter.writeElementString("billNo", "");
                    } else {
                        map = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{query.detail.billNo, query.reqHeader.bankCode});
                        if (map.size() == 0) {
                            detail.respCode = "0";
                            detail.respInfo = "没有找到票据号对应的票据ID号！";
                            retAts.writeDetail(detail);
                            retAts.writeEnd();
                            return retAts;
                        }
                        xmlWriter.writeElementString("billId", map.get("BANKREQSEQID").toString());//票据ID
                        xmlWriter.writeElementString("billNo", query.detail.billNo);
                    }
                    xmlWriter.writeElementString("applicantAcctNo", query.detail.actNum);
                    xmlWriter.writeElementString("status", "");
                    xmlWriter.writeElementString("startTransDt", DateHelper.convertDateTimetoD8(query.detail.operateDate));
                    xmlWriter.writeElementString("endTransDt", DateHelper.convertDateTimetoD8(query.detail.operateDate));
                    xmlWriter.writeElementString("minStartTransDt", "");
                    xmlWriter.writeElementString("maxStartTransDt", "");
                    xmlWriter.writeElementString("minEndTransDt", "");
                    xmlWriter.writeElementString("maxEndTransDt", "");
                    xmlWriter.writeElementString("transType", "2".equals(query.detail.operType) ? "2" : "1");
                    xmlWriter.writeElementString("signFlag", "");
                    xmlWriter.writeElementString("transNo", "");
                    xmlWriter.writeElementString("xTransNo", getQryTransType(query));
                    xmlWriter.writeElementString("statusCode", "");
                    xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
                    xmlWriter.writeElementString("currentPage", String.valueOf(currentPage));
                    xmlWriter.writeElementString("maxBillMoney", "");
                    xmlWriter.writeElementString("minBillMoney", "");
                    xmlWriter.writeElementString("remitter", "");
                    xmlWriter.writeElementString("remitterAcctNo", "");
                    xmlWriter.writeElementString("payee", "");
                    xmlWriter.writeElementString("payeeAcctNo", "");
                    xmlWriter.writeElementString("acceptor", "");
                    xmlWriter.writeElementString("acceptorAcctNo", "");
                    xmlWriter.writeElementString("forbidFlag", "");
                    xmlWriter.writeElementString("directForehand", "");
                    xmlWriter.writeElementString("signDt", "");
                    xmlWriter.writeElementString("billType", "");
                    xmlWriter.writeElementString("sortType", "05");
                    xmlWriter.writeElementString("sortMode", "2");
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();
                    String signXml = getDataSignData(xmlWriter);
                    if (signnatrue(signXml) == true) {
                        xmlWriter.writeElementString("signData", signature);
                        xmlWriter.writeEndDocument();//写入数据完成
                        String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
                        if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmprspcod = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                                String tmprspmsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                                if (isActiveRetCode(tmprspcod)) {
                                    totalPages = Integer.parseInt(tmpBkReader.getFirstText("/HZBANKB2C/ebank/output/totalPages"));
                                    if (0 == tmpBkReader.countElement("/HZBANKB2C/ebank/output/result/row")) {
                                        detail.respCode = "-1";
                                        detail.respInfo = "查无记录";
                                    } else {
                                        int total = 0;
                                        while (tmpBkReader.read("/HZBANKB2C/ebank/output/result/row")) {
                                            String billId = tmpBkReader.readedXElement.getSingleTextNotNull("billId");//票据ID
                                            if (billId.equals(map.get("BANKREQSEQID").toString())) {
                                                total++;
                                                detail.respCode = "0";//响应码
                                                detail.respInfo = tmpBkReader.readedXElement.getSingleTextNotNull("returnMsg");//响应信息
                                                detail.reqSeqID = query.detail.reqSeqID;//交易流水号
                                                detail.billNo = tmpBkReader.readedXElement.getSingleTextNotNull("billNo");//电子票据号码
                                                detail.transState = tmpBkReader.readedXElement.getSingleTextNotNull("returnCode") + tmpBkReader.readedXElement.getSingleTextNotNull("statusCode");//处理状态码
                                                detail.payInfoCode = detail.transState;//交易信息码
                                                detail.billState = getBillStatus(query.detail.actNum, map.get("BANKREQSEQID").toString(), query.reqHeader);//票据状态
                                            }
                                        }
                                        if (total > 1) {
                                            detail = new RetAtsB006BillStateQryDetail();
                                            detail.respCode = "-1";//响应码
                                            detail.respInfo = "查出多条结果数据，系统无法进行区分，请手动确认申请结果";
                                            WriteBankLogLn("查出多条结果数据，系统无法进行区分，请手动确认申请结果");
                                        } else if (total == 0) {
                                            detail = new RetAtsB006BillStateQryDetail();
                                            detail.respCode = "-1";//响应码
                                            detail.respInfo = "未查询到出票结果,请联系银行确认.";
                                            WriteBankLogLn("未查询到出票结果,请联系银行确认.");
                                        }
                                    }
                                } else {
                                    detail.respCode = "-1";
                                    detail.respInfo = tmprspmsg;
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = tmpBkReader.toString();
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = tmpStrRet[1];
                        }

                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSign[1];
                    }
                    retAts.writeDetail(detail);
                } while (currentPage < totalPages);
            }
        } catch (Exception e) {
            RetAtsB006BillStateQryDetail detail = new RetAtsB006BillStateQryDetail();
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            retAts.writeDetail(detail);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    //可追索人查询
    @Override
    public RetAtsB007BillKzsrQry D_B007_BillKzsr_Query(ReqB007BillKzsrQry query) throws Exception {
        RetAtsB007BillKzsrQry retAts = new RetAtsB007BillKzsrQry(query.reqHeader);
        retAts.writeStart();
        retAts.respCode = "-1";
        retAts.respInfo = "银行暂不支持此操作";
        retAts.writeEnd();
        return retAts;
    }

    //历史票据查询
    @Override
    public RetAtsB008HistoricalBillQry D_B008_HistoricalBillQuery(ReqB008HistoricalBillQry query) throws Exception {
        return null;
    }

    //出票登记查询
    @Override
    public RetAtsB009DrawBillQry D_B009_DrawBillQuery(ReqB009DrawBillQry query) throws Exception {
        return null;
    }

    //票据协议状态查询
    @Override
    public RetAtsB010ProtocolStateQry D_B010_ProtocolStateQuery(ReqB010ProtocolStateQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB011TransFlagQry D_B011_TransFlagQuery(ReqB011TransFlagQry query) throws Exception {
        return null;
    }

    /**
     * 票据背面信息查询业务转换
     * 交易类型代码 2  承兑 3  收票 4  撤票 10  背书转让 11  贴现 12  回购式贴现赎回 13  转贴现 14  回购式转贴现赎回 15  再贴现
     * 16  回购式再贴现赎回 25  央行卖出商业汇票 17  保证 18  质押 19  质押解除 20  提示付款 21  逾期提示付款 22  追索 23  追索同意清偿
     *
     * @return
     */
    protected String getTransCode(String billType) {
        String transCode = "";
        if (!StringHelper.isNullOrEmpty(billType)) {
            switch (Integer.parseInt(billType)) {
                case 201002:
                    transCode = "10";
                    break;//背书
                case 201702:
                    transCode = "17";
                    break;//保证
                case 201802:
                    transCode = "18";
                    break;//18  质押
                case 201102:
                    transCode = "11";
                    break;//买断式贴现
                case 201104:
                    transCode = "11";
                    break;//回购式贴现
                case 201202:
                    transCode = "12";
                    break;//回购式贴现赎回
                case 201302:
                    transCode = "13";
                    break;//买断式转贴现
                case 201304:
                    transCode = "13";
                    break;//回购式转贴现
                case 201402:
                    transCode = "14";
                    break;//14  回购式转贴现赎回
                case 201502:
                    transCode = "15";
                    break;//买断式再贴现
                case 201504:
                    transCode = "15";
                    break;//回购式再贴现
                case 201602:
                    transCode = "16";
                    break;//16  回购式再贴现赎回
                case 202502:
                    transCode = "25";
                    break;//25  央行卖出商业汇票
                case 202002:
                    transCode = "20";
                    break;//提示付款
                //case 13:transCode="21";break;//逾期提示付款
                case 202302:
                    transCode = "22";
                    break;//追索
//                case 15:
//                    transCode = "22";
//                    break;//再追索
//                //case 020006:transCode="23";break;//追索同意清偿
                default:
                    transCode = "";
            }
        }
        return transCode;
    }

    //业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
    private String getQryTransType(ReqB006BillStateQry query) {
        String qryTransType = "";
        switch (Integer.valueOf(query.detail.busiType)) {
            case 1:
                qryTransType = "2001";
                break;
            case 2:
                qryTransType = "2002";
                break;
            case 3:
                qryTransType = "2003";
                break;
            case 4:
                qryTransType = "2010";
                break;
            case 5:
                qryTransType = "2018";
                break;
            case 6:
                qryTransType = "2019";
                break;
            case 7:
            case 8:
            case 9:
                qryTransType = "2017";
                break;
            case 10:
                qryTransType = "2011";
                break;
            case 12:
                if ("2".equals(query.detail.overdueFlag)) {
                    qryTransType = "2021";
                } else {
                    qryTransType = "2020";
                }
                break;
        }
        return qryTransType;
    }

    /// 查询类型 1-申请 2-应答 3-撤回
    /// 业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
    private List<String> getTransType(ReqB001OperBillQry query) {
        List<String> transTypes = new ArrayList();
        switch (Integer.parseInt(query.detail.busiType)) {
            case 1://出票
                if ("3".equals(query.detail.queryType)) {//撤回
                    transTypes.add("200401");
                }
                break;
            case 2://承兑
                if ("1".equals(query.detail.queryType)) {//申请
                    transTypes.add("200201");
                } else if ("2".equals(query.detail.queryType)) {//签收
                    transTypes.add("200202");
                } else if ("3".equals(query.detail.queryType)) {//撤回
                    transTypes.add("203201");
                }
                break;
            case 3://收票
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("200301");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("200302");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203202");
                }
                break;
            case 4://背书转让
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201001");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201002");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203203");
                }
                break;
            case 5://质押
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201801");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201802");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203213");
                }
                break;
            case 6://解质押
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201901");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201902");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203214");
                }
                break;
            case 7://出票保证
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201701");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201702");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203215");
                }
                break;
            case 8://承兑保证
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201701");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201702");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203215");
                }
                break;
            case 9://背书保证
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201701");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201702");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203215");
                }
                break;
            case 10://贴现
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201101");//买断式贴现申请
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201102");//买断式贴现签收
                    transTypes.add("201104");//回购式贴现签收
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203204");//买断式贴现申请
                    transTypes.add("203205");//回购式贴现申请
                }
                break;
            case 11://回购式贴现赎回
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("201201");//贴现赎回
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("201202");//贴现赎回
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203206");//贴现赎回
                }
                break;
            case 12://提示付款
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("200005");//提示付款申请汇总
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("202002");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203216");
                    transTypes.add("203217");
                }
                break;
            case 13://追索
                if ("1".equals(query.detail.queryType)) {
                    transTypes.add("200003");
                } else if ("2".equals(query.detail.queryType)) {
                    transTypes.add("200009");
                } else if ("3".equals(query.detail.queryType)) {
                    transTypes.add("203218");
                    transTypes.add("203220");
                }
                break;
//                case 14://同意清偿
//                    transTypes.add("202301");
//                    transTypes.add("202303");
//                    break;
            default:
                throw new RuntimeException("不支持的业务类型");
        }
        return transTypes;
    }

    //根据票据ID查询票据状态
    private String getBillStatus(String actNum, String billId, ReqRespHeader reqHeader) throws Exception {
        String billState = "";
        txCode = "PY4023";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入通用的头部节点
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("input");
        xmlWriter.writeElementString("compFlowNo", reqHeader.transSeqID);//企业流水号
        xmlWriter.writeElementString("billId", billId);//交易类型
        xmlWriter.writeElementString("applicantAcctNo", actNum);//客户账号

        xmlWriter.writeEndElement();
        xmlWriter.writeEndElement();
        String signXml = getDataSignData(xmlWriter);
        if (signnatrue(signXml) == true) {
            xmlWriter.writeElementString("signData", signature);
            xmlWriter.writeEndDocument();//写入数据完成
            String[] tmpStrRet = sendToBank(getDataSendBank(xmlWriter.toXmlString()));//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmprspcod = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retCode");
                    String tmprspmsg = tmpBkReader.getFirstText("/HZBANKB2C/ebank/common/retMsg");
                    if (tmprspcod != null && "000000".equals(tmprspcod)) {
                        billState = tmpBkReader.getFirstTextNotNull("/HZBANKB2C/ebank/output/status");
                    } else {
                        WriteBankLogLn("查询票据状态失败，原因：" + tmprspmsg);
                    }
                } else {
                    WriteBankLogLn("查询票据状态失败，原因：" + tmpSbMsg.toString());
                }
            } else {
                WriteBankLogLn("查询票据状态失败，原因：" + tmpStrRet[1]);
            }
        } else {
            WriteBankLogLn("查询票据状态失败，原因：" + tmpSign[1]);
        }
        return billState;
    }
}
